package com.prj.ufdm.demo.tutorial.zkcurator;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorListenerTest {

		public static void main(String[] args) throws Exception {
			String connectString = "47.98.183.17:2181";
			String ZK_PATH = "/zkcurator/zktest";
			RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
			CuratorFramework client = //CuratorFrameworkFactory.newClient(connectString, retryPolicy);
									 CuratorFrameworkFactory.builder()
						                .connectString(connectString)
						                .retryPolicy(retryPolicy)
						                .sessionTimeoutMs(6000)
						                .connectionTimeoutMs(3000)
						                .namespace("demo")
						                .build();
			client.start();
			setCuratorListenter(client,ZK_PATH);
	        Thread.sleep(Integer.MAX_VALUE);
	}
		
	/**
	 * CuratorListener监听
	 * 此监听主要针对background通知和错误通知。使用此监听器之后，调用inBackground方法会异步获得监听，而对于节点的创建或修改则不会触发监听事件
	 * @param client
	 * @throws Exception
	 */
	private static void setCuratorListenter(CuratorFramework client,String path) throws Exception{
		ExecutorService pool = Executors.newCachedThreadPool();
		CuratorListener curatorListener = new CuratorListener() {
			@Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
            	  System.out.println("监听事件触发，event内容为：" + event);
            }
        };
        client.getCuratorListenable().addListener(curatorListener,pool);
        // 异步获取节点数据
        client.getData().inBackground().forPath(path);
        // 变更节点内容
        client.setData().forPath(path,"123".getBytes());
	}
}
